package com.application.Activity;

import java.util.ArrayList;

import org.apache.http.message.BasicNameValuePair;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

import ReadWriteXML.CMember;
import ReadWriteXML.XMLBuilder;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import com.application.Controller.NetworkController;
import com.application.Controller.ReadWriteFileController;
import com.application.DTO.RoleDTO;
import com.application.Network.Protocol;
import com.application.Tree.BoardView;
import com.application.Tree.INode;
import com.application.Tree.TextNode;
import com.application.Tree.TreeNode;
import com.application.outdoor.InvoikeServices.CayThaoLuanInvoike;
import com.application.outdoor.InvoikeServices.CommonInvoike;
import com.application.outdoor.InvoikeServices.HeThongInvoike;
import com.application.outdoor.InvoikeServices.OperationsInvoike;
import com.application.outdoor.adapter.ContactList;
import com.application.outdoor.adapter.SubjectList;
import com.application.outdoor.pojo.CayThaoLuanPOJO;
import com.application.outdoor.pojo.FileSharePOJO;
import com.application.outdoor.pojo.NguoiDungPOJO;
import com.google.android.gcm.GCMBaseIntentService;

public class GCMIntentService extends GCMBaseIntentService {

	Handler handler;
	public static final String TAG = "GCMIntentService";

	public GCMIntentService() {
		super(Protocol.SENDER_ID);
		handler = new Handler();
	}

	@Override
	protected void onRegistered(Context context, String registrationId) {
		Log.i(TAG, "Device registered: regId = " + registrationId);
		try {
			new HeThongInvoike().register(context);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@Override
	protected void onUnregistered(Context context, String registrationId) {
		Log.i(TAG, "Device unregistered");

	}

	@Override
	protected void onMessage(Context context, Intent intent) {
		if(CommonUtilities.nguoiDung==null)
			return;
		String type = intent.getStringExtra(Protocol.CMD) + "";
		Log.i(TAG, "onMessage type=" + type);
		if (type.equals(Protocol.DANG_NHAP)) {
			int idNguoiDung = Integer.parseInt(intent.getStringExtra(Protocol.ID));
			String tenDangNhap = intent.getStringExtra(Protocol.TEN_DANG_NHAP);
			Log.d("id-tendangnhap", idNguoiDung + "-" + tenDangNhap);
			if (CommonUtilities.nguoiDung == null) {
				CommonUtilities.nguoiDung = new NguoiDungPOJO();
			}
			CommonUtilities.nguoiDung.setId(idNguoiDung);
			CommonUtilities.nguoiDung.setTenDangNhap(tenDangNhap);
		} else if (type.equals(Protocol.TAO_CAY)) {

			int idCay = Integer.parseInt(intent.getStringExtra(Protocol.ID_CAY).trim());
			String nguoiGui = intent.getStringExtra(Protocol.NGUOI_GUI);
			Log.d(TAG,"GCMIntentService: TAO_CAY nguoiGui="+ nguoiGui);
			Log.d(TAG,"GCMIntentService: TAO_CAY nguoidung hiện tại= "+ CommonUtilities.nguoiDung.getTenDangNhap());
			int idNhom = Integer.parseInt(intent.getStringExtra(Protocol.ID_NHOM));
			if (!nguoiGui.equals(CommonUtilities.nguoiDung.getTenDangNhap())) {
//				ArrayList<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
//				params.add(new BasicNameValuePair(Protocol.ID_CAY, idCay + ""));
//				params.add(new BasicNameValuePair(Protocol.NGUOI_GUI, nguoiGui));
//				params.add(new BasicNameValuePair(Protocol.ID_NHOM, idNhom + ""));
				od_VaoThaoLuanActivity.idNhom=idNhom;
				od_VaoThaoLuanActivity.nguoiGui=nguoiGui;
				
				notification(context, nguoiGui+" tạo một chủ đề thảo luận mới!", od_VaoThaoLuanActivity.class, null);				
				CommonUtilities.idCayHienTai = idCay;
				
			}
			try {
				String rs= new CayThaoLuanInvoike().getThongTinCay(idCay);
				CayThaoLuanPOJO cay=new CayThaoLuanPOJO();
				cay.parseFromStringXML(rs);
				CommonUtilities.subjects.addCay(idNhom, cay);
				handler.post(od_SubjectActivity.raRefreshData);
			} catch (Exception e) {
				Log.e(Protocol.TAG,"GCMIntentService.TAO_CAY, tạo cây mới, cập nhật list: "+e.getMessage());
				e.printStackTrace();
			}

		} else if (type.equals(Protocol.JOIN_GROUP)) {
			String nguoiGui = intent.getStringExtra(Protocol.NGUOI_GUI);
			CMember member = new CMember(nguoiGui, nguoiGui, nguoiGui);
			frmNhomChoActivity.insertMember(member);
			
			final ArrayList<CMember> memberList = ReadWriteFileController
					.readMember(ReadWriteFileController.MEMBER_PATH);
			String lstTenDangNhap = "";
			for (CMember m : memberList) {
				lstTenDangNhap += m.get_userName() + ";";
			}

			try {
				// Gửi danh sách nhóm hiện tai cho thanh vien moi join
				new CommonInvoike().guiTinNhan(CommonUtilities.nguoiDung.getTenDangNhap(), nguoiGui, lstTenDangNhap, Protocol.MEMBER_LIST);
				// Gửi tên đăng nhập của người vừa mới join cho các thành viên khác
				for (int i = 0; i < memberList.size(); i++) {
					
					if (!member.get_userName().equals(CommonUtilities.nguoiDung.getTenDangNhap())) {
						new CommonInvoike ().guiTinNhan(CommonUtilities.nguoiDung.getTenDangNhap(), memberList.get(i).get_userName(), nguoiGui,
								Protocol.UPDATE_MEMBER_LIST);
					}
				}
			} catch (Exception e) {
				Log.e(TAG, "Không gửi đc msg update member list tới các thành viên \n" + e.getMessage());
				e.printStackTrace();
			}

			handler.post(frmNhomChoActivity.raRefreshListView);
			Log.d(TAG, "nguoi gui id=" + nguoiGui + " danh sach thanh vien =" + lstTenDangNhap);
		} else if (type.equals(Protocol.UPDATE_MEMBER_LIST)) {
			String tenDangNhap = intent.getStringExtra(Protocol.NOI_DUNG);
			String nguoiGui = intent.getStringExtra(Protocol.NGUOI_GUI).trim();
			
			if (!nguoiGui.equals(CommonUtilities.nguoiDung.getTenDangNhap())) {				
				CMember member = new CMember(tenDangNhap,tenDangNhap,tenDangNhap);
				frmNhomChoActivity.insertMember(member);
				handler.post(frmNhomChoActivity.raRefreshListView);
			}
		} else if (type.equals(Protocol.MEMBER_LIST)) {

			String nguoiGui = intent.getStringExtra(Protocol.NGUOI_GUI).trim();
			if (!nguoiGui.equals(CommonUtilities.nguoiDung.getTenDangNhap())) {
				String ids = intent.getStringExtra(Protocol.NOI_DUNG);
				Log.d(TAG, "member list=" + ids);
				String[] m = ids.split(";");
			
				
				ReadWriteFileController.deleteFile(ReadWriteFileController.MEMBER_PATH);
				for (int i = 0; i < m.length; i++) {
					CMember member = new CMember(m[i],m[i],m[i]);
					frmNhomChoActivity.insertMember(member);
				}
				int idNhom = CommonUtilities.idNhomHienTai;
				Intent i = new Intent(context, frmNhomChoActivity.class);
				i.putExtra(frmTaoNhom.CODE_GROUP_NAME, CommonUtilities.contacts.getGroupByID(idNhom).getTenNhom());
				NetworkController.setGroupName(CommonUtilities.contacts.getGroupByID(idNhom).getTenNhom());
				i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				startActivity(i);
				
				//moi them
//				Message msg=new Message();
//				Bundle b=new Bundle();
//				b.putString("KEY", "DIS");
//				msg.setData(b);
//				handler.sendMessage(msg);
				//
			}
		} else if (type.equals(Protocol.SET_ROLE)) {
			String noiDung = intent.getStringExtra(Protocol.NOI_DUNG);
			String path = ReadWriteFileController.MY_ROLE_PATH;
			ReadWriteFileController.writeRole(path,
					RoleDTO.parseList(MESApplication.getAppContext(), noiDung, ReadWriteFileController.RULE_BASE_PATH));
			NetworkController.resetRole();
		} else if (type.equals(Protocol.START_GROUP)) {
			NetworkController._peer.getAccount().inGroup = true;
			handler.post(frmNhomChoActivity.raStartGroup);
		}else if(type.equals(Protocol.THEM_NODE)){
			String noiDung=intent.getStringExtra(Protocol.NOI_DUNG);
			Log.d(TAG, noiDung);
				Document doc=null;
				try {
					doc = XMLBuilder.loadXMLFromString(noiDung);
				} catch (Exception e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
				Element e=(Element) doc.getElementsByTagName("TreeNode").item(0);
				TreeNode node=new TreeNode();
				TextNode textnode=new TextNode();
				
				node.readXML(e);
				textnode.readXML(e);
				
				
				frmTreeNodeActivity.idNode=node.getParentID();
				frmTreeNodeActivity.nodeAdd=node;
				frmTreeNodeActivity.textnodeAdd=textnode;
				Log.d("Phu"," NetWorkLayer-AddNode..." + frmTreeNodeActivity.isActive);
				if(frmTreeNodeActivity.isActive){
					Log.d("Phu"," NetWorkLayer-AddNode...active nen cho vao cay luon");
					handler.post(frmTreeNodeActivity.raAddnode);
					handler.post(frmTreeNodeActivity.raAddnodetext);
				}
				else{
					Log.d(TAG,"GCMIntentService-AddNode...ko active nen ghi xuong file node: " + node.getId());					
					TreeNode tree = new TreeNode();
					if(ReadWriteFileController.isFile(BoardView.treePath)){							
						tree.readXml(BoardView.treePath);
						Log.d(TAG,"GCMIntentService-AddNode...File tồn tại nên đọc từ file lên: "+tree.getSumChildren());
					}else{
						Log.d(TAG,"GCMIntentService-AddNode...Ko tồn tại file nên createRoot: "+tree.getSumChildren());
						tree=BoardView.createRoot();
					}
					INode temp = tree.getById(node.getParentID());
					if (temp != null){
						Log.d(TAG,"GCMIntentService-AddNode...add node: " + node.getId()+" vào node " + temp.getId());
						temp.add(node);
						tree.setVersion(node.getVersion());
						Log.d(TAG,"GCMIntentService-AddNode...add node: " + tree.getSumChildren());
					}
					tree.writeXML(BoardView.treePath);
				}
			
			
		}else if(type.equals(Protocol.XOA_NODE)) {
			try {
				String s = intent.getStringExtra(Protocol.NOI_DUNG);
				INode node = new TreeNode();
				INode tnode = new TextNode();
				Document doc;

				doc = XMLBuilder.loadXMLFromString(s);

				Element e = (Element) doc.getElementsByTagName("TreeNode").item(0);
				node.readXML(e);
				tnode.readXML(e);
				
				frmTreeNodeActivity.nodeAdd = (TreeNode) node;
				frmTreeNodeActivity.textnodeAdd = (TextNode) tnode;
				if (frmTreeNodeActivity.isActive) {
					Log.d("An", "active nên delete luôn");
					handler.post(frmTreeNodeActivity.raDeleteNode);
					//handler.post(frmTreeNodeActivity.raDeleteNodeText);
				} else {
					Log.d("An", "delete ko active nên xóa ghi xuống file");

					TreeNode tree = new TreeNode();
					tree.readXml(BoardView.treePath);
					INode temp = tree.getById(node.getId());
					if (temp != null) {
						tree.remove(temp);
						tree.setVersion(node.getVersion());
						tree.writeXML(BoardView.treePath);
					}

				}
			} catch (Exception e1) {
				Log.d(TAG,"GCMIntentService - Không thể Xóa node");
				Log.d(TAG, e1.getMessage());
				e1.printStackTrace();
			}
		}else if(type.equals(Protocol.CAP_NHAT_NODE)){
			try {
				String s = intent.getStringExtra(Protocol.NOI_DUNG);
				TreeNode node = new TreeNode();
				TextNode textnode = new TextNode();
				Document doc = XMLBuilder.loadXMLFromString(s);
				Element e = (Element) doc.getElementsByTagName("TreeNode").item(0);
				node.readXML(e);
				textnode.readXML(e);				
				frmTreeNodeActivity.nodeAdd = node;
				frmTreeNodeActivity.textnodeAdd = textnode;
				if (frmTreeNodeActivity.isActive) {
					Log.d("Phu", "Active nên update vào cây luôn");
					handler.post(frmTreeNodeActivity.raUpdateTextNode);
					//handler.post(frmTreeNodeActivity.raUpdateNodeText);
				} else {
					Log.d("Phu","update ko active cap nhat xuong file");
					TreeNode tree=new TreeNode();
					if(ReadWriteFileController.isFile(BoardView.treePath)){						
						tree.readXml(BoardView.treePath);						
					}else{
						tree=BoardView.createRoot();
					}
					INode temp= tree.getById(node.getId());
					if(temp!=null){
						temp.copy(node);
					}
					tree.writeXML(BoardView.treePath);
				}
			} catch (Exception e) {
				Log.d(TAG,"GCMIntentService - Không thể cập nhật node");
				Log.d(TAG, e.getMessage());
			}
		}else if(type.equals(Protocol.GUI_TIN_NHAN)){
			int msgType=Integer.parseInt(intent.getStringExtra(Protocol.MSG_TYPE));
			if(msgType==1){//mời nhóm
				ArrayList<BasicNameValuePair> params=new ArrayList<BasicNameValuePair>();
				params.add(new BasicNameValuePair(Protocol.NOI_DUNG, intent.getStringExtra(Protocol.NOI_DUNG)));
				params.add(new BasicNameValuePair(Protocol.NGUOI_GUI, intent.getStringExtra(Protocol.NGUOI_GUI)));
				params.add(new BasicNameValuePair(Protocol.ID, intent.getStringExtra(Protocol.ID)));
				notification(context, "Lời mời vào nhóm!", od_TraLoiVaoNhomActivity.class, params);
			}
			else if(msgType==0){//chat
				Log.v(TAG,"nhan dc CHAT_PEER_MESSAGE");
				new OperationsInvoike().receiveChatPeerMess(intent);
			}
		}else if(type.equals(Protocol.CAP_NHAT_CONTACT)){
			int idNhom=Integer.parseInt(intent.getStringExtra(Protocol.ID_NHOM));
			try {
				String rs=new CommonInvoike().getContact(idNhom);
				ContactList contact=new ContactList();
				contact.init(rs);
				 for(int i=0;i<CommonUtilities.contacts.getSize();i++){
					 if(CommonUtilities.contacts.getGroup(i).getId()==idNhom){
						 CommonUtilities.contacts.getData().set(i, contact.getData().get(0));
						 handler.post(od_ContactActivity.raRefreshData);
						 return;
					 }
				 }
				
			} catch (Exception e) {
				Log.d(TAG,"không GCMIntentSerive CAP_NHAT_CONTACT:"+e.getMessage());
				e.printStackTrace();
			}			
		}else if(type.equals(Protocol.CAP_NHAT_SUBJECT)){
			int idNhom=Integer.parseInt(intent.getStringExtra(Protocol.ID_NHOM));
			try{
				String rs=new CommonInvoike().getSubject(idNhom);
				SubjectList subject=new SubjectList();
				subject.init(rs);
				for(int i=0;i<CommonUtilities.subjects.getSize();i++){
					if(CommonUtilities.subjects.getGroup(i).getId()==idNhom){
						CommonUtilities.subjects.getData().set(i, subject.getData().get(0));
						handler.post(od_SubjectActivity.raRefreshData);
					}
				}
			}catch (Exception e) {
				// TODO: handle exception
			}
		}else if(type.equals(Protocol.SHARE_FILE)){
			String noiDung=intent.getStringExtra(Protocol.NOI_DUNG);
			final ArrayList<FileSharePOJO> lstFile=FileSharePOJO.parseList(noiDung);
			String msg=lstFile.get(0).getNguoiUp()+" mới chia sẻ tập tin: "+lstFile.get(0).getTenFile();
			if(!lstFile.get(0).getNguoiUp().equals(CommonUtilities.nguoiDung.getTenDangNhap())){	
				od_fileInfoActivity.file=lstFile.get(0);
				od_fileInfoActivity.open=false;
				notification(context, msg, od_fileInfoActivity.class, null);
			}else if(od_ShareFileActivity.isOpen){
				handler.post(new Runnable() {
					
					@Override
					public void run() {
						// TODO Auto-generated method stub
						od_ShareFileActivity.addFile(lstFile.get(0));
					}
				}) ;
			}
			
	}
		else if(type.equals(Protocol.KICK_MEMBER_OUT_MESSAGE)){
			Log.v(TAG,"nhan dc KICK_MEMBER_OUT_MESSAGE");
			new OperationsInvoike().receiveVoteKickMember(intent);				
		}
		else if(type.equals(Protocol.KICK_MEMBER_OUT_FEEDBACK)){
			Log.v(TAG,"nhan dc KICK_MEMBER_OUT_FEEDBACK");
			new OperationsInvoike().receiveFeedbackKickMember(intent);
		}
		else if(type.equals(Protocol.KICK_MEMBER_OUT_RESULT)){
			Log.v(TAG,"nhan dc KICK_MEMBER_OUT_RESULT");
			new OperationsInvoike().receiveResultKickMember(intent);
		}
		else if(type.equals(Protocol.STOP_TALKING_ONE_MEMBER)){
			Log.v(TAG,"nhan dc STOP_TALKING_ONE_MEMBER");
			new OperationsInvoike().receiveStopTalkMember(intent);
		}
		else if(type.equals(Protocol.ACCEPT_TALKING_ONE_MEMBER)){
			Log.v(TAG,"nhan dc ACCEPT_TALKING_ONE_MEMBER");
			new OperationsInvoike().receiveAcceptTalkMember(intent);
		}
//		else if(type.equals(Protocol.CHAT_PEER_MESSAGE)){
//			Log.v(TAG,"nhan dc CHAT_PEER_MESSAGE");
//			new OperationsInvoike().receiveChatPeerMess(intent);
//		}
		else if(type.equals(Protocol.CHAT_FEEDBACK_NON_RULE)){
			Log.v(TAG,"nhan dc CHAT_FEEDBACK_NON_RULE");
			new OperationsInvoike().receiveChatPeerNoneRule(intent);
		}
		else if(type.equals(Protocol.GROUP_BIEU_QUYET)){
			Log.v(TAG,"nhan dc GROUP_BIEU_QUYET");
			new OperationsInvoike().receiveBieuQuyet(intent);
		}
		else if(type.equals(Protocol.GROUP_DANH_GIA)){
			Log.v(TAG,"nhan dc GROUP_DANH_GIA");
			new OperationsInvoike().receiveDanhGia(intent);
		}
		else if(type.equals(Protocol.BIEU_QUYET_FEEDBACK)){
			Log.v(TAG,"nhan dc BIEU_QUYET_FEEDBACK");
			new OperationsInvoike().receiveBieuQuyetFeedback(intent);
		}
		else if(type.equals(Protocol.RESULT_BIEU_QUYET)){
			Log.v(TAG,"nhan dc RESULT_BIEU_QUYET");
			new OperationsInvoike().receiveBieuQuyetResult(intent);
		}
		else if(type.equals(Protocol.DANH_GIA_FEEDBACK)){
			Log.v(TAG,"nhan dc DANH_GIA_FEEDBACK");
			new OperationsInvoike().receiveDanhGiaFeedback(intent);
		}
		else if(type.equals(Protocol.RESULT_DANH_GIA)){
			Log.v(TAG,"nhan dc RESULT_DANH_GIA");
			new OperationsInvoike().receiveDanhGiaResult(intent);
		}
		else if(type.equals(Protocol.CLEAR_NODE_TREE)){
			Log.v(TAG,"nhan dc CLEAR_NODE_TREE");
			new OperationsInvoike().receiveStopDiscuss(intent);
		}
		else{		
			Log.e(TAG, "GCmIntentService onMessage Không hiểu đây là loại gì");
		}
		
	}

	@Override
	protected void onDeletedMessages(Context context, int total) {
		Log.i(TAG, "Received deleted messages notification");
	}

	@Override
	public void onError(Context context, String errorId) {
		Log.i(TAG, "Received error: " + errorId);
	}

	@Override
	protected boolean onRecoverableError(Context context, String errorId) {
		return super.onRecoverableError(context, errorId);
	}

//	private static void generateNotification(Context context, String message) {
//		int icon = R.drawable.ic_accept;
//		long when = System.currentTimeMillis();
//		NotificationManager notificationManager = (NotificationManager) context
//				.getSystemService(Context.NOTIFICATION_SERVICE);
//		Notification notification = new Notification(icon, message, when);
//		String title = context.getString(R.string.app_name);
//		Intent notificationIntent = new Intent(context, od_DangNhapActivity.class);
//		// set intent so it does not start a new activity
//		notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
//		PendingIntent intent = PendingIntent.getActivity(context, 0, notificationIntent, 0);
//		notification.setLatestEventInfo(context, title, message, intent);
//		notification.flags |= Notification.FLAG_AUTO_CANCEL;
//		notificationManager.notify(0, notification);
//	}

	public static void notification(Context context, String message, Class<?> activity,
			ArrayList<BasicNameValuePair> params) {
		int icon = R.drawable.ic_accept;
		long when = System.currentTimeMillis();
		NotificationManager notificationManager = (NotificationManager) context
				.getSystemService(Context.NOTIFICATION_SERVICE);
		Notification notification = new Notification(icon, message, when);
		notification.defaults|=Notification.DEFAULT_SOUND;
		String title = context.getString(R.string.app_name);
		PendingIntent intent;
		if (activity != null) {
			Intent notificationIntent = new Intent(context, activity);
			if (params != null) {
				for (BasicNameValuePair p : params) {
					notificationIntent.putExtra(p.getName(), p.getValue());
					// Log.d(TAG,"notification putExtra: name-value"+p.getName()+"-"+p.getValue());
				}
			}
			// set intent so it does not start a new activity
			notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
			intent = PendingIntent.getActivity(context, 0, notificationIntent, 0);
		} else {
			intent = PendingIntent.getActivity(context, 0, null, 0);
		}
		notification.setLatestEventInfo(context, title, message, intent);
		notification.flags |= Notification.FLAG_AUTO_CANCEL;
		notificationManager.notify(0, notification);
		Log.d(TAG,"Tạo notification");
	}
}
